package com.flyone.fuxiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyone.fuxiao.annotation.AuthCheck;
import com.flyone.fuxiao.common.BaseResponse;
import com.flyone.fuxiao.common.ErrorCode;
import com.flyone.fuxiao.common.ResultUtils;
import com.flyone.fuxiao.exception.BusinessException;
import com.flyone.fuxiao.model.dto.note.NoteQueryRequest;
import com.flyone.fuxiao.model.dto.note.NoteSaveRequest;
import com.flyone.fuxiao.model.entity.User;
import com.flyone.fuxiao.model.entity.UserNote;
import com.flyone.fuxiao.model.vo.UserNoteVO;
import com.flyone.fuxiao.service.UserNoteService;
import com.flyone.fuxiao.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 笔记 控制类
 *
 * @author flyone
 * @date 2024/4/19
 */
@RestController
@RequestMapping("/note")
@Api(tags = "日记相关接口")
public class NoteController {

    @Resource
    private UserService userService;

    @Resource
    private UserNoteService userNoteService;
    /**
     * 保存日记内容
     * @param diarySaveRequest
     * @param request
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "笔记保存")
    public BaseResponse<Long> saveDiary(@RequestBody NoteSaveRequest diarySaveRequest, HttpServletRequest request){
        if (diarySaveRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();

        long diaryId = userNoteService.saveWrite(diarySaveRequest, userId);

        return ResultUtils.success(diaryId);
    }

    /**
     * 获取日记内容
     * @param request
     * @return
     */
    @GetMapping("/get")
    @ApiOperation(value = "获取笔记")
    public BaseResponse<List<UserNoteVO>> getDiary(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        QueryWrapper<UserNote> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        List<UserNote> userNoteList = userNoteService.list(queryWrapper);
        List<UserNoteVO> userNoteVOList = userNoteList.stream().map(userNote -> {
            UserNoteVO userNoteVO = new UserNoteVO();
            BeanUtils.copyProperties(userNote, userNoteVO);
            int moodIndex = calculateSentimentIndex(userNote.getSentiment(), userNote.getConfidence(),
                    userNote.getPositiveProb(), userNote.getNegativeProb());
            userNoteVO.setMoodIndex(moodIndex);
            return userNoteVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(userNoteVOList);
    }

    /**
     * 删除日记
     * @param request
     * @return
     */
    @PostMapping("/remove/{id}")
    @ApiOperation(value = "删除笔记")
    public BaseResponse<String> DeleteNote(@PathVariable("id") Long id,
                                                     HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser != null){
            boolean result = userNoteService.removeById(id);
        }
        return ResultUtils.success("删除成功");
    }

    @PostMapping("/list")
    @AuthCheck(mustRole = "admin")
    @ApiOperation(value = "获取笔记列表")
    public BaseResponse<Page<UserNote>> getNoteList(@RequestBody NoteQueryRequest noteQueryRequest, HttpServletRequest request){
        userService.isAdmin(request);
        long current = noteQueryRequest.getCurrent();
        long pageSize = noteQueryRequest.getPageSize();
        Page<UserNote> page = userNoteService.page(new Page<>(current, pageSize), userNoteService.getQueryWrapper(noteQueryRequest));
        return ResultUtils.success(page);
    }

    public static int calculateSentimentIndex(int sentiment, double confidence, double positiveProb, double negativeProb) {
        // 如果置信度低于一定阈值，可以返回中性
        if (confidence < 0.5) {
            return 50;
        }

        // 根据情感分类计算倾向指数
        switch (sentiment) {
            case 0: // 负向
                return (int) (50 - (50 * negativeProb));
            case 1: // 中性
                return 50;
            case 2: // 正向
                return (int) (50 + (50 * positiveProb));
            default:
                throw new IllegalArgumentException("Invalid sentiment value");
        }
    }
}
